package xyz.zhzby.cyzx.security.security;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.ApiModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zby
 * @date 2021/12/07
 */
@ApiModel("token操作工具类")
@Component
public class TokenManager {

    private final String TOKEN_SIGN_KEY = "cyzx";

    public String createToken(String username, Long tokenExpiration) {
        return "Bearer " + Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY).compressWith(CompressionCodecs.GZIP).compact();
    }

    public String getUserFromToken(String token) {
        return Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token).getBody().getSubject();
    }

    public void removeToken(RedisTemplate redisTemplate, String userName) {
        redisTemplate.delete("loginUser:info:" + userName);
        redisTemplate.delete("loginUser:auth:" + userName);
    }

}
